#!/usr/bin/perl -w

# The purpose of this short tool is to return to standard output
# one or more free ports common across all nodes.
#
# It makes use of the common_requests object to do the work,
# and will return:
# OK port port ...
#
# ERROR - msg
#

BEGIN {
	if(!exists($::ENV{TRUECL_CODE})) {
		die("Missing TRUECL_CODE environment variable.");
	}
	if(!exists($::ENV{TRUECL_LOG})) {
		die("Missing TRUECL_LOG environment variable.");
	}
	if(!exists($::ENV{TRUECL_CFG})) {
		die("Missing TRUECL_CFG environment variable.");
	}
	if(! -d "$::ENV{TRUECL_CODE}/clreqd_modules") {
		die("Missing clreqd_modules directory in $::ENV{TRUECL_CODE}.");
	}
	push @::INC,"$::ENV{TRUECL_CODE}/lib";
	$::PKI=1;
	eval "use Crypt::RSA;";
	$::PKI=0 if $@;
}

use strict;
use common_requests;
use clreqdxml;
use cllogging;

$::ARG_parallel=0;
$::ARG_timeout=10;
$::ARG_width=80;


#########################################################################
# Put in command line argument processing here and a usage msg.		#
#########################################################################

$::LOGGER=new cllogging("-",$::ARG_width);

if(!defined($::LOGGER)) {
	print STDERR "Error: Unable to initialise logging object.\n";
	exit 1;
}

$::LOGGER->set_verbose;
$::CLREQD=new clreqdxml("$::ENV{TRUECL_CFG}/clreqd.xml");
if(!defined($::CLREQD)) {
	$::LOGGER->msg("error","Unable to open/parse file $::ENV{TRUECL_CFG}/clreqd.xml - aborting.");
	$::LOGGER->msg("error","MSG from object: ".clreqdxml->error);
	exit 1;
}
$::LOGGER->msg("msg","Initialised 'cluster request daemon interface' object successfully.");

$::COMMON=new common_requests(timeout=>$::ARG_timeout,parallel=>$::ARG_parallel,clreqdxml=>$::CLREQD);
if(!defined($::COMMON)) {
	$::LOGGER->msg("error","Unable to initialise 'common requests' object.");
	exit 1;
}

$::LOGGER->msg("msg","Initialised 'common requests' object successfully.");

# At this point we've got to do some real work!!

($::list,$::err)=$::COMMON->get_common_free_port(count=>1);
if(!defined($::list)) {
	$::LOGGER->msg("error","No results returned from 'get_common_free_port' call.");
	$::LOGGER->msg("error"," [$::err]");
	exit 1;
}

for (@$::list) {
	print "$_\n";
}
exit(0);
